package cn.cdqf.web;

import cn.cdqf.common.ResultResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
public class UploadServlet {

    @RequestMapping("/photoupload")
    @ResponseBody
    public ResultResponse upload(@RequestParam("file") MultipartFile file, HttpSession httpSession) throws IOException {
        String originalFilename = file.getOriginalFilename();

        String[] splits = originalFilename.split("\\.");
        String fileName = UUID.randomUUID().toString()+"."+splits[splits.length-1];

        String contextPath = httpSession.getServletContext().getRealPath("/media/images");
        contextPath = contextPath+"/"+fileName;

        file.transferTo(new File(contextPath));
        ResultResponse resultResponse = new ResultResponse(200, fileName);
        return resultResponse;
    }

}
